import { createApi, toast } from '@halobear/request'

import { baseURL } from '@/constants'
import store from '@/store'

import { useApiCache } from './preload-tools'

const clientRquest = createApi({
  config: { baseURL, shouldLoading: false, shouldToast: true },
  requestHandler(config) {
    const { token } = store.state.user.user || {}
    config.headers = {
      ...config.headers,
      'X-Halo-App': 'app-travel-merchant',
    }
    token && (config.headers.Authorization = `Bearer ${token}`)
  },
  errorHandler(e) {
    const { status } = (e || {}).response || {}
    if (status === 401) {
      store.dispatch('logout')
    }
  },
})

const offlineRequest = async (options) => {
  const { url, shouldToast = true } = options
  const { id } = store.state.user.user
  const res = await useApiCache(url, id)
  if (!res && shouldToast) {
    toast('数据未找到')
    return Promise.reject(new Error('数据未找到'))
  }
  return res.data
}

export default (options) => {
  const { method = 'get' } = options
  const { mode = 'offline' } = store.state.config
  if (method === 'get' && mode === 'offline') return offlineRequest(options)
  return clientRquest(options)
}
